//! @Author: DengLibin
//! @Date: Create in 2023-11-06 17:19:55
//! @Description: 路由
use crate::{
    config, controller,
    global::{check_result, AppState, GlobalResult},
    midware,
};
use axum::Extension;
use axum::{
    extract::DefaultBodyLimit,
    middleware,
    routing::{get, post},
    Router,
};
use log::info;
use rust_common::mysql::MysqlClient;
use std::sync::Arc;
use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};

/// @Author: DengLibin
/// @Date: Create in 2023-11-06 17:28:09
/// @Description: 创建路由
pub fn new(config: config::AppConfig) -> GlobalResult<(config::AppConfig, Router)> {
    //初始化mysql连接
    let mysql_client = check_result(MysqlClient::new(&config.mysql_url))?;
    info!("mysql 连接成功");
    let shared_state = Arc::new(AppState { mysql_client });

    let mut router = Router::new();

    //路由
    router = router.route("/", get(controller::hello_world::hello_world));
    router = router.route("/test_log", get(controller::hello_world::test_log));
    
    //请求体
    router = router.route("/string_body", post(controller::hello_world::string_body));
    router = router.route("/request", post(controller::hello_world::request));
    //get查询参数
    router = router.route("/query", get(controller::hello_world::query));
    //接收json数组
    router = router.route("/json_arr", post(controller::hello_world::json_arr));
    //接送json对象
    router = router.route("/json_obj", post(controller::hello_world::json_obj));
    //接收表单提交
    router = router.route("/form_obj", post(controller::hello_world::form_obj));
    //上传文件
    router = router.route("/upload", post(controller::hello_world::upload));
    //响应json
    router = router.route("/json", get(controller::hello_world::json));
    //查询数据库
    router = router.route("/user/list", get(controller::user_controller::list));

    //中间件 照添加顺序，后添加的最先进来最后出去
    //禁用requestbody大小限制(上传大文件)
    router = router.layer(DefaultBodyLimit::disable());

    router = router.layer(middleware::from_fn(midware::my_middleware));
    //用户验证
    router = router.layer(middleware::from_fn(midware::auth::auth));
    //计时
    router = router.layer(middleware::from_fn(midware::timing::timing));

    //跨域配置
    let cors_layer = CorsLayer::new()
        .allow_origin(AllowOrigin::any())
        .allow_headers(AllowHeaders::any())
        .allow_methods(AllowMethods::any());

    router = router.layer(cors_layer);

    //共享状态
    router = router.layer(Extension(shared_state));

    Ok((config, router))
}
